package in.co.codedoc.json;

import java.io.IOException;
import java.io.InputStream;

import org.antlr.runtime.ANTLRInputStream;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.CommonTokenStream;

public abstract class JSONValue
{
	public abstract StringBuffer Encode(StringBuffer buffer);

	public static JSONValue Decode(InputStream is,String source)
	{
		try
		{
			return Decode(new ANTLRInputStream(is),source);
		}
		catch(IOException ioe)
		{
			throw new RuntimeException("Failed to read from '" + source + "' : " + ioe.getMessage(),ioe);
		}
	}
	
	public static JSONValue Decode(String payload)
	{
		return Decode(new ANTLRStringStream(payload),payload);
	}
	
	private static JSONValue Decode(CharStream stream,String source)
	{
		try
		{
			JSONParser parser 
				= new JSONParser(new CommonTokenStream(new JSONLexer(stream)));
		
			return parser.jsonPayload();
		}
		catch(Throwable th)
		{
			throw new RuntimeException("Failed to parse '" + source + "' : " + th.getMessage(),th);
		}
	}
	
	public String Encode()
	{
		return Encode(new StringBuffer()).toString();
	}
	
	public abstract int hashCode();
	public abstract boolean equals(Object t);
	
	public String toString()
	{
		return Encode();
	}
}
